import { Col, Descriptions, Row, Tag, Typography, Tabs, Table } from 'antd';
import React from 'react';
import { forEach } from 'lodash';
import CodeEditor from '@/components/CodeEditor';

const { Item } = Descriptions;
const { Text } = Typography;
const { TabPane } = Tabs;

export const MethodTagColors = {
  GET: '4bb793',
  POST: 'D07C35',
  PUT: '1e81e0',
  DELETE: 'dc4f20',
  PATCH: 'CF2F87',
};

export const columns = [
  {
    dataIndex: 'headerName',
    title: 'KEY',
  },
  {
    dataIndex: 'headerValue',
    title: 'VALUE',
  },
];

export function createHeadersDataSource(headers) {
  const dataSource = [];
  forEach(headers, (headerValues, headerName) => {
    headerValues.forEach(headerValue => {
      dataSource.push({
        headerName,
        headerValue,
      });
    });
  });
  return dataSource;
}

function createFormDataSource(formData) {
  const parts = formData.parts || [];
  return parts.map(({ name, body }) => ({ headerName: name, headerValue: body }));
}

function createFormBodySource(formBody) {
  const pairs = formBody.nameValuePairs || [];
  return pairs.map(({ name, value }) => ({ headerName: name, headerValue: value }));
}

function HttpRequestInfo({ request = {} }) {
  const { bodyString: requestBody, headers: requestHeaders, formData, formBody } = request || {};
  return (
    <Tabs defaultActiveKey="body">
      <TabPane tab="Body" key="body">
        {formData ? (
          <Table
            columns={columns}
            dataSource={createFormDataSource(formData)}
            pagination={false}
            bordered
          />
        ) : formBody ? (
          <Table
            columns={columns}
            dataSource={createFormBodySource(formBody)}
            pagination={false}
            bordered
          />
        ) : (
          <CodeEditor readOnly data={requestBody} height={550} />
        )}
      </TabPane>
      <TabPane tab="Header" key="header">
        <Table
          columns={columns}
          dataSource={createHeadersDataSource(requestHeaders)}
          pagination={false}
          bordered
        />
      </TabPane>
    </Tabs>
  );
}

function HttpResponseInfo({ response = {} }) {
  const { bodyString: responseBody, headers: responseHeaders, responseStatus } = response || {};
  return (
    <Tabs defaultActiveKey="body">
      <TabPane tab="Body" key="body">
        <CodeEditor readOnly data={responseBody} height={550} />
      </TabPane>
      <TabPane tab="Header" key="header">
        <Table
          columns={columns}
          dataSource={createHeadersDataSource(responseHeaders)}
          pagination={false}
          bordered
        />
      </TabPane>
      <TabPane tab="Status" key="status">
        <span style={{ color: '#037f31' }} className="margin-left">
          {responseStatus}
        </span>
      </TabPane>
    </Tabs>
  );
}

function HttpCallTaskContent({ content }) {
  let { request, response, options } = content;
  const { requestBeforeIntercept, responseBeforeIntercept } = content;

  request = request || {};
  response = response || {};
  options = options || {};

  const { method, url } = request;
  const { timeoutMilliSeconds = 0 } = options;

  return (
    <>
      <Descriptions column={4}>
        <Item label="是否Mock" span={1}>
          {content.isMock ? '是' : '否'}
        </Item>
        <Item label="超时时间" span={1}>
          {timeoutMilliSeconds / 1000} 秒
        </Item>
        <Item label="拦截器类名" span={2}>
          <Text copyable={!!content.interceptorClassName}>{content.interceptorClassName}</Text>
        </Item>
        <Item label="接口地址" span={4}>
          <Tag color={`#${MethodTagColors[method]}`}>{method}</Tag> <Text copyable>{url}</Text>
        </Item>
      </Descriptions>
      <Row gutter={16} style={{ marginBottom: 16 }}>
        <Col span={12}>
          <Text>HTTP请求</Text>
          <HttpRequestInfo request={request} />
        </Col>
        <Col span={12}>
          <Text>HTTP响应</Text>
          <HttpResponseInfo response={response} />
        </Col>
      </Row>
      {content.interceptorClassName && (
        <Row gutter={16}>
          <Col span={12}>
            <Text>HTTP请求（拦截前）</Text>
            <HttpRequestInfo request={JSON.parse(requestBeforeIntercept)} />
          </Col>
          <Col span={12}>
            <Text>HTTP响应（拦截前）</Text>
            <HttpResponseInfo response={JSON.parse(responseBeforeIntercept)} />
          </Col>
        </Row>
      )}
    </>
  );
}

export default HttpCallTaskContent;
